<template>
  <div
    class="post_panel"
    ref="postForm"
    :model="postForm"
    v-loading="loading"
    body="true"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <!-- 用户发布贴文输入框 -->
    <div class="p_input">
      <el-input
        type="textarea"
        :autosize="{ minRows: 5, maxRows: 5 }"
        :placeholder="$t('userpost.placeholder')"
        v-model="postForm.post_content"
        :maxlength="auth_input_limit"
        resize="none"
        show-word-limit
      >
      </el-input>
    </div>
    <!-- 放置上传图片 -->
    <!-- 上传后的图片所在位置 -->
    <div class="upload_img_panel">
      <!-- 显示一张图片 -->
      <div v-if="uploadImgList.length == 1">
        <div
          class="up_img_item_single"
          v-for="(item, index) in uploadImgList"
          :key="index"
        >
          <img :src="item.imgsrc" class="imgpic" alt="" />
          <div class="del_img_btn" @click="delImg(index)">
            <div class="del_btn_panel">
              <svg viewBox="0 0 24 24" aria-hidden="true">
                <g>
                  <path
                    d="M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z"
                  ></path>
                </g>
              </svg>
            </div>
          </div>
        </div>
      </div>
      <!-- 显示多张图片 -->
      <div class="mulit-list-pic" v-else>
        <div
          class="up_img_item"
          v-for="(item, index) in uploadImgList"
          :key="index"
        >
          <img :src="item.imgsrc" class="imgpic" alt="" />
          <div class="del_img_btn" @click="delImg(index)">
            <div class="del_btn_panel">
              <svg viewBox="0 0 24 24" aria-hidden="true">
                <g>
                  <path
                    d="M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z"
                  ></path>
                </g>
              </svg>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 上传短视频所在位置 -->
    <div class="upload_video_panel">
      <div
        class="up_video_item"
        v-for="(item, index) in uploadVideoList"
        :key="index"
      >
        <video width="500" height="200" class="video" controls>
          <source :src="item.videosrc" type="video/mp4" />
        </video>
        <div class="del_v_btn" @click="delVideo(index)">
          <div class="del_btn_panel">
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <g>
                <path
                  d="M10.59 12L4.54 5.96l1.42-1.42L12 10.59l6.04-6.05 1.42 1.42L13.41 12l6.05 6.04-1.42 1.42L12 13.41l-6.04 6.05-1.42-1.42L10.59 12z"
                ></path>
              </g>
            </svg>
          </div>
        </div>
      </div>
    </div>
    <div class="tools_panel">
      <!-- 左边工具 -->
      <div class="input_tools">
        <!-- 输入菜单工具item-表情包 -->
        <!-- 表情包弹出 -->
        <el-popover
          placement="bottom"
          trigger="click"
          v-model="showEmotVisible"
          class="el-popove-emo"
        >
          <!-- 弹出表情包 -->
          <div class="emot_panel">
            <div class="it" v-for="(item, index) in emot_list" :key="index">
              <img
                @click="select_emot(item.id)"
                :src="item.src"
                :alt="item.id"
              />
            </div>
          </div>
          <!-- 输入菜单工具item-表情包 -->
          <div class="item" slot="reference">
            <div>
              <svg viewBox="0 0 24 24" aria-hidden="true">
                <g>
                  <path
                    d="M8 9.5C8 8.119 8.672 7 9.5 7S11 8.119 11 9.5 10.328 12 9.5 12 8 10.881 8 9.5zm6.5 2.5c.828 0 1.5-1.119 1.5-2.5S15.328 7 14.5 7 13 8.119 13 9.5s.672 2.5 1.5 2.5zM12 16c-2.224 0-3.021-2.227-3.051-2.316l-1.897.633c.05.15 1.271 3.684 4.949 3.684s4.898-3.533 4.949-3.684l-1.896-.638c-.033.095-.83 2.322-3.053 2.322zm10.25-4.001c0 5.652-4.598 10.25-10.25 10.25S1.75 17.652 1.75 12 6.348 1.75 12 1.75 22.25 6.348 22.25 12zm-2 0c0-4.549-3.701-8.25-8.25-8.25S3.75 7.451 3.75 12s3.701 8.25 8.25 8.25 8.25-3.701 8.25-8.25z"
                  ></path>
                </g>
              </svg>
            </div>
            <div class="svg_txt">{{ $t("userpost.emot") }}</div>
          </div>
        </el-popover>
        <!-- 输入菜单工具item-图片上传 -->
        <input
          id="uploadimg"
          type="file"
          ref="postuploader"
          accept=".jpg, .jpeg, .bmp, .gif, .png"
          multiple="multiple"
          class="upload_hidden"
          @change="addUploadImg"
          :disabled="isAddImgEnable"
        />
        <!-- 上传输入框放在外面，否则会被执行两次 -->
        <div
          :class="isAddImgEnable ? 'item disable' : 'item'"
          @click="addPreviewImg()"
        >
          <div>
            <svg viewBox="0 0 24 24" aria-hidden="true">
              <g>
                <path
                  d="M3 5.5C3 4.119 4.119 3 5.5 3h13C19.881 3 21 4.119 21 5.5v13c0 1.381-1.119 2.5-2.5 2.5h-13C4.119 21 3 19.881 3 18.5v-13zM5.5 5c-.276 0-.5.224-.5.5v9.086l3-3 3 3 5-5 3 3V5.5c0-.276-.224-.5-.5-.5h-13zM19 15.414l-3-3-5 5-3-3-3 3V18.5c0 .276.224.5.5.5h13c.276 0 .5-.224.5-.5v-3.086zM9.75 7C8.784 7 8 7.784 8 8.75s.784 1.75 1.75 1.75 1.75-.784 1.75-1.75S10.716 7 9.75 7z"
                ></path>
              </g>
            </svg>
          </div>
          <div class="svg_txt">{{ $t("userpost.picture") }}</div>
        </div>
        <!-- 上传视频 -->
        <input
          id="uploadvideo"
          type="file"
          ref="postuploadVideo"
          accept="video/mp4,video/x-m4v,video/*,.mkv,.flv"
          multiple="multiple"
          class="upload_hidden"
          @change="addUploadVideo"
          :disabled="isAddImgEnable"
        />
        <!-- 输入菜单工具item 视频 -->
        <div
          :class="isAddVideoEnable ? 'item disable' : 'item'"
          @click="addPreviewVideo()"
        >
          <div>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              fill="currentColor"
              viewBox="0 0 16 16"
            >
              <path
                d="M6 6.883v4.234a.5.5 0 0 0 .757.429l3.528-2.117a.5.5 0 0 0 0-.858L6.757 6.454a.5.5 0 0 0-.757.43z"
              />
              <path
                d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"
              />
            </svg>
          </div>
          <div class="svg_txt">{{ $t("userpost.video") }}</div>
        </div>
        <!-- 输入菜单工具item 新话题 -->
        <div class="item" @click="addTitle">
          <div>
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              fill="currentColor"
              viewBox="0 0 16 16"
            >
              <path
                d="M8.39 12.648a1.32 1.32 0 0 0-.015.18c0 .305.21.508.5.508.266 0 .492-.172.555-.477l.554-2.703h1.204c.421 0 .617-.234.617-.547 0-.312-.188-.53-.617-.53h-.985l.516-2.524h1.265c.43 0 .618-.227.618-.547 0-.313-.188-.524-.618-.524h-1.046l.476-2.304a1.06 1.06 0 0 0 .016-.164.51.51 0 0 0-.516-.516.54.54 0 0 0-.539.43l-.523 2.554H7.617l.477-2.304c.008-.04.015-.118.015-.164a.512.512 0 0 0-.523-.516.539.539 0 0 0-.531.43L6.53 5.484H5.414c-.43 0-.617.22-.617.532 0 .312.187.539.617.539h.906l-.515 2.523H4.609c-.421 0-.609.219-.609.531 0 .313.188.547.61.547h.976l-.516 2.492c-.008.04-.015.125-.015.18 0 .305.21.508.5.508.265 0 .492-.172.554-.477l.555-2.703h2.242l-.515 2.492zm-1-6.109h2.266l-.515 2.563H6.859l.532-2.563z"
              />
            </svg>
          </div>
          <div class="svg_txt">{{ $t("userpost.title") }}</div>
        </div>
      </div>
      <!-- 右边发布按钮 -->
      <div class="btn_panel">
        <el-button @click="addPosthandler" size="mini" round>{{
          $t("index.post")
        }}</el-button>
      </div>
    </div>
    <!-- 进度条/加载提示 -->
    <!-- <div v-if="loading" class="loading">
      <img :src="loadingImg" alt="" />
    </div> -->
  </div>
</template>
<script>
//请求公共API接口不能带着header，否则报错，所以请求公共API获取ip需要使用独立的axios
import axios from "axios";

//获取统一请求接口
import { getDetailsUserGlobalInfo,addPostHandler } from "@/api";

export default {
  name: "UserPost",
  props: {
    msg: String,
  },
  data() {
    return {
      postMessage: "",
      uploadImgList: [],
      uploadVideoList: [],
      isAddImgEnable: false, //图片上传是否可用
      isAddVideoEnable: false, //视频上传是否可用
      showEmotVisible: false,
      showAddImgVisible: false,
      auth_input_limit: JSON.parse(localStorage.getItem("user"))
        .auth_input_limit
        ? JSON.parse(localStorage.getItem("user")).auth_input_limit
        : 300,
      emot_num: 84,
      emot_list: [],
      emot_title: "心相印",
      src: "https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg", //上传图片
      loading: false,
      postForm: {
        user_id: JSON.parse(localStorage.getItem("user")).user_id,
        post_content: "",
        sp_url: "",
        tp_url: "",
        post_replylimit: 1,
        post_ip: localStorage.getItem("ip"),
        post_lan_ip: "",
        post_location: "",
        post_city: "",
        post_country: "",
        post_regionName: "",
        post_lat: "",
        post_lon: "",
        zf_parent_id: 0,
        pl_parent_id: 0,
        zf_user_id: 0,
        reply_user_id: 0,
        reply_user_account: "",
      },
    };
  },
  mounted() {
    this.init_emot();
  },
  methods: {
    //通过IP请求公共API获取国家/地区信息
    async getLocationFromIP(ip) {
      let res = await getDetailsUserGlobalInfo(ip);

      if (res.status) {
        this.postForm.post_location =
          res.regionName + " " + res.city + " " + res.isp;
        this.postForm.post_city = res.city;
        this.postForm.post_regionName = res.regionName;
        this.postForm.post_country = res.country;
        this.postForm.post_lat = res.lat;
        this.postForm.post_lon = res.lon;
        // console.log(this.postForm);
      }
    },
    // 获取用户IP地址
    getUserIP(onNewIP) {
      let MyPeerConnection =
        window.RTCPeerConnection ||
        window.mozRTCPeerConnection ||
        window.webkitRTCPeerConnection;
      let pc = new MyPeerConnection({
        iceServers: [],
      });
      let noop = () => {};
      let localIPs = {};
      let ipRegex =
        /([0-9]{1,3}(\.[0-9]{1,3}){3}|[a-f0-9]{1,4}(:[a-f0-9]{1,4}){7})/g;
      let iterateIP = (ip) => {
        if (!localIPs[ip]) onNewIP(ip);
        localIPs[ip] = true;
      };
      pc.createDataChannel("");
      pc.createOffer()
        .then((sdp) => {
          sdp.sdp.split("\n").forEach(function (line) {
            if (line.indexOf("candidate") < 0) return;
            line.match(ipRegex).forEach(iterateIP);
          });
          pc.setLocalDescription(sdp, noop, noop);
        })
        .catch((reason) => {
          console.log(reason);
        });
      pc.onicecandidate = (ice) => {
        if (
          !ice ||
          !ice.candidate ||
          !ice.candidate.candidate ||
          !ice.candidate.candidate.match(ipRegex)
        )
          return;
        ice.candidate.candidate.match(ipRegex).forEach(iterateIP);
      };
    },
    //初始化表情包
    init_emot() {
      //初始化方法
      var _this = this;
      //默认生成表情列表
      for (let i = 1; i <= _this.emot_num; i++) {
        var emot = new Object();
        emot.id = i;
        emot.src = require("@/assets/img/emot/2023_" + i + ".png");
        _this.emot_list.push(emot);
      }
    },
    showEmot() {
      this.showEmotVisible = !this.showEmotVisible;
    },
    //选中表情操作
    select_emot(e) {
      //根据点击表情id生成快捷文字
      var el = e;
      var em_text = "[2023_" + el + "]";
      //关闭表情选择器并将内容赋值到input表签内
      this.showEmotVisible = false;
      //console.log("test:"+em_text)
      //console.log(this.replace_em(testdata))
      this.postForm.post_content += em_text;
    },
    addTitle() {
      this.postForm.post_content = "#新话题#" + this.postForm.post_content;
    },
    delImg(idx) {
      this.uploadImgList.forEach((item, index) => {
        if (index == idx) {
          this.uploadImgList.splice(idx, 1);
        }
      });
      //上传图片超过4张 上传禁用
      this.setImgEnable();
    },
    //点击触发上传按钮
    addPreviewImg() {
      let _this = this;
      let input = _this.$refs.postuploader; // document.getElementById("uploadimg");
      input.click(); //模拟点击
    },
    //封装图片文件方法
    addUploadImg() {
      let _this = this;
      let input = _this.$refs.postuploader; // document.getElementById("uploadimg");
      let reader = new FileReader();
      let file = input.files[0];
      const limitSize = file.size / 1024 / 1024 < 2;
      if (!limitSize) {
        this.$message({
          message: "上传文件限制最大为2MB",
          type: "warning",
        });
        return;
      }
      reader.readAsDataURL(file);
      reader.onload = function () {
        let imgsrc = reader.result; //this.result
        _this.uploadImgList.push({ imgsrc: imgsrc, file: file });
        //图片超过4张禁止继续上传
        _this.setImgEnable();
      };
    },
    //封装判断上传图片列表长度小于4张则可以上传，否则禁用
    setImgEnable() {
      let counts = this.uploadImgList.length;
      if (counts > 0) {
        this.isAddVideoEnable = true;
      } else {
        this.isAddVideoEnable = false;
      }
      // console.log(counts);
      if (counts < 4) {
        this.isAddImgEnable = false;
      } else {
        this.isAddImgEnable = true;
      }
    },
    addPreviewVideo() {
      let _this = this;
      let input = _this.$refs.postuploadVideo; // document.getElementById("uploadimg");
      input.click(); //模拟点击
    },
    addUploadVideo() {
      let _this = this;
      let input = _this.$refs.postuploadVideo; // document.getElementById("uploadimg");
      let reader = new FileReader();
      let file = input.files[0];
      const limitSize = file.size / 1024 / 1024 < 20;
      if (!limitSize) {
        this.$message({
          message: "上传文件限制最大为20MB",
          type: "warning",
        });
        return;
      }
      reader.readAsDataURL(file);
      reader.onload = function () {
        let videosrc = reader.result; //this.result
        _this.uploadVideoList.push({ videosrc: videosrc, file: file });
        //上传视频则禁用上传图片
        _this.setVideoEnable();
      };
    },
    //设置视频上传禁用图片上传
    setVideoEnable() {
      if (this.uploadVideoList.length > 0) {
        this.isAddImgEnable = true;
        this.isAddVideoEnable = true;
      } else {
        this.isAddImgEnable = false;
        this.isAddVideoEnable = false;
      }
    },
    delVideo(idx) {
      this.uploadVideoList.forEach((item, index) => {
        if (index == idx) {
          this.uploadVideoList.splice(idx, 1);
        }
      });
      //上传视频则禁用上传图片
      this.setVideoEnable();
    },
    //上传图片和上传视频发帖方法整合
    async addUploadPostHandler() {
      //打开进度
      this.loading = true;
      //新建变量FormData
      const formData = new FormData();
      //添加信息数据
      formData.append("user_id", this.postForm.user_id);
      formData.append("zf_parent_id", this.postForm.zf_parent_id);
      formData.append("pl_parent_id", this.postForm.pl_parent_id);
      //被转发用户的id
      formData.append("zf_user_id", this.postForm.zf_user_id);
      formData.append("reply_user_id", this.postForm.reply_user_id);
      formData.append("reply_user_account", this.postForm.reply_user_account);
      formData.append("post_content", this.postForm.post_content);
      formData.append("post_replylimit", this.postForm.post_replylimit);
      formData.append("post_ip", this.postForm.post_ip);
      formData.append("post_lan_ip", this.postForm.post_lan_ip);
      formData.append("post_location", this.postForm.post_location);
      formData.append("post_city", this.postForm.post_city);
      formData.append("post_country", this.postForm.post_country);
      formData.append("post_regionName", this.postForm.post_regionName);
      formData.append("post_lat", this.postForm.post_lat);
      formData.append("post_lon", this.postForm.post_lon);

      //从uploadImgList拿出要上传的图片
      this.uploadImgList.forEach((item) => {
        formData.append("image", item.file);
      });
      //从uploadVideoList拿出要上传的视频
      this.uploadVideoList.forEach((item) => {
        formData.append("video", item.file);
      });

      //调用文件上传请求方法
      let res = await addPostHandler(formData);
      if (res.state == 200) {
        //显示上传文件的路径信息
        //触发父组件刷新数据
        this.$emit("reflashed");
        //消息提示
        this.$message({
          message: res.message,
          type: "success",
        });
      } else {
        this.$message({
          message: res.message,
          type: "warning",
        });
      }
      this.loading = false;
      this.initPostForm();
    },
    //发布帖子
    async addPosthandler() {
      //发帖前判断发帖内容不能为空
      if (
        this.postForm.post_content.trim() == "" ||
        this.postForm.post_content == null
      ) {
        this.$message({
          message: "发布内容不能为空",
          type: "warning",
        });
        return;
      }
      //发布的时候再获取用户ip地址信息
      //初始化局域网IP
      this.getUserIP((ip) => {
        this.postForm.post_lan_ip = ip;
      });
      await this.getLocationFromIP(this.postForm.post_ip);
      this.addUploadPostHandler();
    },
    initPostForm() {
      this.uploadImgList = [];
      this.uploadVideoList = [];
      this.postForm.post_content = "";
      this.isAddImgEnable = false;
      this.isAddVideoEnable = false;
    },
  },
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.post_panel {
  padding: 18px 18px 10px 18px;
  border-bottom: 1px solid rgb(239, 243, 244);
  /* border-bottom-style: solid;
  border-bottom-width: 1px;
  border-bottom-color: rgb(239, 243, 244); */
}

.input_textarea {
  border: 1px solid #ff8200;
  border-radius: 5px;
  padding: 6px 11px;
  /* border-width: 1px;
    border-color: #ff8200;
    border-radius: 5px; */
}

.p_input {
  width: 100%;
}

.p_input /deep/ .el-textarea__inner {
  border-color: #ff8200;
}

.post_input_box {
  width: 100%;
  height: 90px;
  resize: none;
  padding: 0;
  background: transparent;
  border: none;
  -webkit-box-shadow: none;
  box-shadow: none;
  outline: none;
  font-size: 15px;
}

.input_tools {
  display: flex;
  margin: 15px 0;
  /* color: #838383; */
  color: rgb(29, 155, 240);
  font-size: 14px;
}

.input_tools .item {
  display: flex;
  position: relative;
  margin-right: 8px;
  cursor: pointer;
}

.input_tools .item svg {
  width: 1.25rem;
  height: 1.25rem;
  fill: rgb(29, 155, 240);
}

.input_tools .disable {
  color: rgba(29, 155, 240, 0.4);
  cursor: not-allowed;
}

.input_tools .disable svg {
  fill: rgba(29, 155, 240, 0.4);
}

.svg_txt {
  margin: 0 6px 0 4px;
  line-height: 18px;
}

.btn_panel {
  height: 30px;
  margin: 15px 0;
}

.btn_panel button {
  border: 0;
  background: #ff8200;
  color: #fff;
}

.tools_panel {
  display: flex;
  justify-content: space-between;
}

/* 表情包样式 */
.emot_panel {
  display: flex;
  flex-wrap: wrap;
  padding: 5px;
  width: 432px;
  background-color: #fff;
  /* border: 1px solid #e9e9e9; */
  /* border-radius: 10px; */
  /* box-shadow: 0 0.125rem 0.25rem 0 rgba(0, 0, 0, 0.1); */
  z-index: 99;
}

.emot_panel .it {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 8.333%;
  height: 38px;
  text-align: center;
}

.emot_panel .it:hover {
  cursor: pointer;
  border-radius: 50%;
  background-color: #f3e3d1;
}

.emot_panel .it img {
  width: 24px;
  height: 24px;
}

/* 图片上传 */

.upload_img_panel {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.upload_img_panel .up_img_item {
  display: flex;
  position: relative;
  max-width: 500px;
  width: 246px;
  /* height: 164px; */
  margin-right: 4px;
  margin-bottom: 4px;
}

.upload_img_panel .imgpic {
  max-width: 500px;
  min-width: 246px;
  border-radius: 10px;
}
.up_img_item_single {
  position: relative;
  max-width: 500px;
}

.up_img_item_single .imgpic {
  max-width: 480px;
  max-height: 360px;
  border-radius: 15px;
  margin-bottom: 10px;
}

.up_img_item .del_img_btn,
.up_img_item_single .del_img_btn {
  position: absolute;
  top: 4px;
  right: 4px;
  z-index: 39;
  cursor: pointer;
}

.mulit-list-pic {
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.del_btn_panel {
  display: flex;
  justify-content: center;
  width: 20px;
  height: 20px;
  background-color: rgba(15, 20, 25, 0.5);
  border-radius: 50%;
  line-height: 29px;
}

.del_btn_panel svg {
  width: 18px;
  height: 18px;
  fill: rgba(252, 255, 255, 1);
}

/* 默认隐藏上传输入框 */
.upload_hidden {
  display: none;
}

/* 图片样式结束 */

.loading {
  display: flex;
  justify-content: center;
}

/* 上传视频 */
.upload_video_panel {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  align-content: flex-start;
}

.up_video_item {
  display: flex;
  position: relative;
  max-width: 500px;
}

.up_video_item .del_v_btn {
  position: absolute;
  top: 4px;
  right: 4px;
  z-index: 39;
  cursor: pointer;
}

.up_video_item .video {
  display: flex;
  align-items: center;
  justify-content: center;
  max-width: 500px;
  max-height: 200px;
  flex: 1;
}

@media screen and (max-width: 720px) {
  .emot_panel {
    width: 340px;
  }

  .up_video_item .video {
    flex: 1;
    width: 100%;
    max-height: 300px;
  }
}

@media screen and (max-width: 400px) {
  .emot_panel {
    width: 340px;
  }

  .up_video_item .video {
    flex: 1;
    width: 100%;
    max-height: 300px;
  }

  .up_img_item_single .imgpic {
    flex: 1;
    width: 100%;
    max-height: 300px;
  }
}
</style>